/**
    Copyright (c) 2010 ATTi 
    All rights reserved.
    Author: Michael Shu
    Date: 5/25/2010
*/

public class EmailSentFromCaseHelperClass {
    public static String User_Prefix =  GeneralConstants.User_Prefix;
    public static String Case_Prefix =  GeneralConstants.Case_Prefix;
    public static String EmailMessage_Prefix =  GeneralConstants.EmailMessage_Prefix;
    public static set<String> RT_CCIR = GeneralConstants.RT_CCIR;
    
    public static String SFDC_NO_Reply_Email = GeneralConstants.SFDC_NO_Reply_Email;
    public static String NO_Reply_Label = GeneralConstants.NO_Reply_Label;
    private static Id orgWideEmailId;
    
    public static set<ID> getClosedCCIRCaseIds(list<Attachment> attachments){
    	set<ID> allcsIds = new set<ID>();
    	for( Attachment a : attachments ) {
    		String tPrefix = String.Valueof(a.parentId).subString(0,3);	
    		if(tPrefix == Case_Prefix){
    			allcsIds.add(a.parentId);
    		}
        }
        if(!allcsIds.isEmpty()){
        	return (new Map<Id, Case>([select Id from Case where Id IN: allcsIds and isClosed = true and RecordType.Name IN: RT_CCIR])).keySet();
        }
    	return new set<ID>();
    }
    
    public static Boolean sendEmailtoCaseOwnerIfDifferent(Set<ID> cIDs, String title){
        Boolean rst = true;
        if((cIDs != null && !cIDs.isEmpty())){
        	List<Case> cases;
        	Map<ID, Case> cases_with_userOwner = new Map<ID, Case>();
        	ID curUserId = UserInfo.getUserId();
            if(cIDs != null){
            	cases = [select Id, Account.Name, Contact.Name, Owner.Name, Owner.Email, Owner.Profile.Name, CSS_CustomerID__c, Status, IR_Priority__c, 
            	                OwnerId, CaseNumber, Subject, RecordTypeId, RecordType.Name
                         from Case 
                         where Id IN: cIDs
                           and OwnerId !=: curUserId 
                           and isClosed = false
                           and RecordType.Name IN: RT_CCIR];
                for(Case c : cases){
            	    String tPrefix = String.Valueof(c.OwnerId).subString(0,3);
	                if(tPrefix == User_Prefix){
	                    cases_with_userOwner.put(c.Id, c);
	                }
                }
            }
            if(!cases_with_userOwner.isEmpty()){
                Integer size = cases_with_userOwner.size();
                System.debug('Test size = ' + size);
                Messaging.SingleEmailMessage[] lmail = new Messaging.SingleEmailMessage[size];
                Id noReplyEmailId = getSFDCnoReplyEmailOrgWideId();
                Integer i = 0;
                for(Case c : cases_with_userOwner.values()){
                	set<String> toEmails = new set<String>();
                	toEmails.add(c.Owner.Email);
                    String emailTitle = title;
                    lmail[i] = getEmail(c, toEmails,emailTitle, noReplyEmailId);
                    i++;    
                }
                try{
                    Messaging.SendEmailResult[] eResult = Messaging.sendEmail(lmail); // send email
                    for(Messaging.SendEmailResult r : eResult){
                        System.debug('Email Result eResult.isSuccess() = ' + r.isSuccess());
                    }
                }catch(Exception ex){
                    GeneralConstants.mailAnyExceptionToMe('EmailSentFromCaseHelperClass', 'Send Notice Email Fail', ex);
                    System.debug('Email Fail: Send Notice Email Fail');
                    System.debug(ex);
                    rst = false;
                }
            }           
        }
        return rst;
    }

    public static Messaging.SingleEmailMessage getEmail(Case c, set<String> toEmails, String title, ID noReplyEmailId){
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        list<String> listToEmails = new list<String>();
        listToEmails.addAll(toEmails);
        mail.setToAddresses(listToEmails);
        System.debug('Test mail.getToAddresses()[0] = ' + mail.getToAddresses()[0]);
        String accountName = (c.Account.Name == null)? 'n/a': c.Account.Name;
        String contactName = (c.Contact.Name == null)? 'n/a' : c.Contact.Name;
        String cssCustomerId = (c.CSS_CustomerID__c == null)? 'n/a' : c.CSS_CustomerID__c;
        String cSubject = (c.Subject == null)? 'n/a' : c.Subject;
        String recordTypeName = c.RecordType.Name;
        String subject = 'DO NOT REPLY – AT&T IOG Case Owner Notification: ' + c.CaseNumber + ' - ' + accountName;
        mail.setSubject(subject);
        if(noReplyEmailId != null){
        	mail.setOrgWideEmailAddressId(noReplyEmailId);
        }else{
	        mail.setSenderDisplayName(NO_Reply_Label);
	        mail.setReplyTo(SFDC_NO_Reply_Email);
        }
        String HtmlEmailContent = 
+ '<p/>'
+ 'AT&T IOG Case Owner Notification for: ' + c.Owner.Name  
+ '<p/>'
+ 'An event has occured on this SalesForce.com Case: ' + c.CaseNumber
+ '<p/>'
+ 'Event Type: ' + title
+ '<p/>'     
+ '<table border="0">'
+ '<tr><td width="200">Case Number : </td><td>' + c.CaseNumber + '</td></tr>'
+ '<tr><td width="200">Case Record Type : </td><td>' + recordTypeName + '</td></tr>'
+ '<tr><td width="200">Case Subject : </td><td>' + cSubject + '</td></tr>'
+ '<tr/>'
+ '<tr><td width="200">Account Name: </td><td>' + accountName + '</td></tr>'
+ '<tr><td width="200">CSS Customer ID: </td><td>' + cssCustomerId + '</td></tr>'
+ '<tr><td width="200">Contact Name: </td><td>' + contactName + '</td></tr>'
+ '</table>'
+ '<p/>'
+ 'You have received this notification because you are listed as the Case Owner on a Case in the IOG SalesForce.com system.'
+ '<p/>'
+ 'For any other Interactive Ad questions please contact AT&T Advertisting Solutions Customer Support.'
+ '<p/>';
        mail.setsaveAsActivity(false);
        mail.setHtmlBody(HtmlEmailContent); 
        return mail;
    }
    
    private static ID getSFDCnoReplyEmailOrgWideId(){
    	if(orgWideEmailId == null){
	    	OrgWideEmailAddress[] orgWideEmails = [Select Id from OrgWideEmailAddress where Address =: SFDC_NO_Reply_Email]; 
			if(orgWideEmails.size() > 0){
				orgWideEmailId = orgWideEmails[0].Id;
			}
    	}
    	return orgWideEmailId;
    }
}